package appcus

import (
	"counter-help/admin/server/global"
	customerReq "counter-help/admin/server/model/app/request"
	customerRes "counter-help/admin/server/model/app/response"
	"counter-help/admin/server/model/customer"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"io"
	"mime/multipart"
	"os"
	"strconv"
)

type CusOrderService struct{}

// CreateCusOrder 创建 cusOrder 表记录
func (cusOrderService *CusOrderService) CreateCusOrder(user_id int, cusOrder *customerReq.CreateCusOrder, file *multipart.FileHeader, c *gin.Context) (err error) {
	// 检查用户是否已有订单
	var existingOrder customer.CusOrder
	isFirst := true
	if err := global.GVA_DB.Where("order_user_id = ?", user_id).First(&existingOrder).Error; err == nil {
		isFirst = false
	}

	// 初始化 CusOrder 结构体
	order := customer.CusOrder{
		Title:         cusOrder.Title,
		AnRequire:     cusOrder.AnRequire,
		BussType:      cusOrder.BussType,
		Status:        1,
		ItemType:      cusOrder.ItemType,
		BudgetMin:     cusOrder.BudgetMin,
		BudgetMax:     cusOrder.BudgetMax,
		UrgencyDegree: cusOrder.UrgencyDegree,
		Deadline:      cusOrder.Deadline,
		Specialty:     cusOrder.Specialty,
		OrderUserId:   user_id,
		IsFirst:       &isFirst,
	}

	// 检查是否传递了 Background 字段
	if cusOrder.Background != "" {
		order.Background = cusOrder.Background
	}
	if cusOrder.Other != "" {
		order.Other = cusOrder.Other
	}

	// 创建订单
	if err = global.GVA_DB.Create(&order).Error; err != nil {
		return err
	}

	// 如果上传了文件，保存文件到本地并更新 Attach 字段
	var filePath string
	if file != nil {
		filePath, err = saveFileToLocal(file, int(order.ID), user_id, c)
		if err != nil {
			return err
		}
		order.Attach = filePath
		// 更新订单的 Attach 字段
		if err = global.GVA_DB.Model(&order).Update("attach", filePath).Error; err != nil {
			return err
		}
	}

	return nil
}

// `saveFileToLocal` 函数更新
// 更新后的 saveFileToLocal 函数
func saveFileToLocal(file *multipart.FileHeader, orderID, userID int, c *gin.Context) (string, error) {
	savePath := fmt.Sprintf("uploads/orders/%d/%d/", userID, orderID)
	// 创建目录
	if err := os.MkdirAll(savePath, os.ModePerm); err != nil {
		return "", fmt.Errorf("创建存储目录失败: %w", err)
	}

	// 文件存储路径
	filePath := savePath + file.Filename
	out, err := os.Create(filePath)
	if err != nil {
		return "", fmt.Errorf("文件保存失败: %w", err)
	}
	defer out.Close()

	// 保存文件内容到目标文件
	src, err := file.Open()
	if err != nil {
		return "", fmt.Errorf("文件打开失败: %w", err)
	}
	defer src.Close()

	if _, err := io.Copy(out, src); err != nil {
		return "", fmt.Errorf("文件写入失败: %w", err)
	}

	return filePath, nil
}

// DeleteCusOrder 删除 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) DeleteCusOrder(ID string) (err error) {
	err = global.GVA_DB.Delete(&customer.CusOrder{}, "id = ?", ID).Error
	return err
}

// DeleteCusOrderByIds 批量删除 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) DeleteCusOrderByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]customer.CusOrder{}, "id in ?", IDs).Error
	return err
}

// UpdateCusOrder 更新 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) UpdateCusOrder(cusOrder customer.CusOrder) (err error) {
	err = global.GVA_DB.Model(&customer.CusOrder{}).Where("id = ?", cusOrder.ID).Updates(&cusOrder).Error
	return err
}

// GetCusOrderInfoList 分页获取 cusOrder 表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusOrderService *CusOrderService) GetCusOrderInfoList(info customerReq.CusOrderSearch) (list []customer.CusOrder, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

	// 创建 db
	db := global.GVA_DB.Model(&customer.CusOrder{})
	var cusOrders []customer.CusOrder

	// 如果有条件搜索，下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&cusOrders).Error
	return cusOrders, total, err
}

// GetAllCusOrders 获取所有订单记录以及每个订单的接单人数
// Author [Your Name]
func (cusOrderService *CusOrderService) GetAllCusOrders() ([]customerRes.CusOrderListResponse, error) {
	var orders []customer.CusOrder
	err := global.GVA_DB.Where("status = 3").Find(&orders).Error
	if err != nil {
		return nil, err
	}

	var orderResponses []customerRes.CusOrderListResponse

	for _, order := range orders {
		// 查询每个订单的接单人数
		var assignmentCount int64
		err := global.GVA_DB.Model(&customer.CusOrderAssignments{}).
			Where("order_id = ?", order.ID).
			Count(&assignmentCount).Error
		if err != nil {
			return nil, err
		}

		// 构造单独返回结构体
		//orderResponse := customerRes.CusOrderWithAssignmentCountResponse{
		//	Order: convertCusOrderToResponse(order),
		//	//AssignmentCount: assignmentCount, // 单独返回接单人数
		//}

		orderResponses = append(orderResponses, convertCusOrderToResponse(order))
	}

	return orderResponses, nil
}

// GetOrdersByUserID 根据用户 ID 获取订单列表
func (cusOrderService *CusOrderService) GetOrdersByUserID(userID int, sortBy string, queryStr string) ([]customerRes.CusOrderListResponse, error) {
	var orders []customer.CusOrder

	// 设置排序条件
	var orderCondition string
	switch sortBy {
	case "时间由近及远":
		orderCondition = "created_at DESC"
	case "时间由远及近":
		orderCondition = "created_at ASC"
	case "价格由低到高":
		orderCondition = "budget_max ASC"
	case "价格由高到低":
		orderCondition = "budget_max DESC"
	default:
		orderCondition = "created_at DESC"
	}

	// 构建查询条件
	query := global.GVA_DB.Where("order_user_id = ?", userID).Order(orderCondition)

	// 如果 queryStr 不为空，添加模糊查询条件
	if queryStr != "" {
		queryStrInt, err := strconv.Atoi(queryStr)
		if err == nil {
			// 如果 queryStr 能转换为整数，则匹配 id
			query = query.Where("id = ?", queryStrInt)
		} else {
			// 否则匹配 title、AnRequire、ItemType 字段
			query = query.Where("title LIKE ? OR AnRequire LIKE ? OR ItemType LIKE ?",
				"%"+queryStr+"%", "%"+queryStr+"%", "%"+queryStr+"%")
		}
	}

	// 执行查询
	err := query.Find(&orders).Error
	if err != nil {
		return nil, err
	}

	// 转换查询结果为响应对象
	var orderResponses []customerRes.CusOrderListResponse
	for _, order := range orders {
		orderResponses = append(orderResponses, convertCusOrderToResponse(order))
	}

	return orderResponses, nil
}

// GetCusOrderByID 根据订单 ID 获取单个订单
func (cusOrderService *CusOrderService) GetCusOrderByID(orderID string) (customerRes.CusOrderListResponse, error) {
	var order customer.CusOrder
	err := global.GVA_DB.Where("id = ?", orderID).First(&order).Error
	if err != nil {
		return customerRes.CusOrderListResponse{}, err
	}

	return convertCusOrderToResponse(order), nil
}

// FilterCusOrderList 根据传入的查询条件筛选 CusOrder
func (cusOrderService *CusOrderService) FilterCusOrderList(userID int, params customerReq.SearchParams) (list []customerRes.CusOrderListResponse, total int64, err error) {
	db := global.GVA_DB.Debug().Model(&customer.CusOrder{})
	// 处理紧急程度筛选
	if params.UrgencyDegree != 888 {
		db = db.Where("urgency_degree = ?", params.UrgencyDegree)
	}
	if params.ItemType != "" {
		db = db.Where("item_type = ?", params.ItemType)
	}
	if params.BussType != "" && params.BussType != "全部" {
		db = db.Where("buss_type = ?", params.BussType)
	}

	// 预算筛选
	if params.BudgetMin != nil {
		db = db.Where("budget_min >= ?", *params.BudgetMin)
	}
	if params.BudgetMax != nil {
		db = db.Where("budget_max <= ?", *params.BudgetMax)
	}
	if params.Specialty != "" {
		db = db.Where("specialty = ?", params.Specialty)
	}
	db = db.Where("status = ?", 3)
	// 排序
	if params.SortBy != "" {
		switch params.SortBy {
		case "价格最高":
			db = db.Order("budget_max DESC") // 按预算最高降序
		case "价格最低":
			db = db.Order("budget_max ASC") // 按预算最低升序
		case "最新发布":
			db = db.Order("created_at DESC") // 按创建时间降序
		default:
			// 可选：处理无效的排序值
		}
	}

	// 获取记录总数
	err = db.Count(&total).Debug().Error
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	var orders []customer.CusOrder
	// 查询订单数据
	err = db.Find(&orders).Debug().Error
	if err != nil {
		return nil, 0, err
	}

	var orderResponses []customerRes.CusOrderListResponse

	// 遍历订单，检查收藏状态、接单状态，并转换为响应结构
	for _, order := range orders {
		var isFavorited bool
		var isAssignment bool

		// 查询收藏记录
		var favorite customer.CusOrderFavorite
		err := global.GVA_DB.Where("user_id = ? AND order_id = ?", userID, order.ID).First(&favorite).Error
		if err == nil {
			isFavorited = true // 如果查询到了收藏记录，则标记为已收藏
		} else if !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, 0, err // 如果发生其他错误，则直接返回
		}

		// 查询用户信息
		var user customer.CusUser
		err = global.GVA_DB.Where("id = ?", order.OrderUserId).First(&user).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, 0, err // 如果发生其他错误，则返回错误
		}

		// 查询接单状态
		var assignment customer.CusOrderAssignments
		err = global.GVA_DB.Where("order_id = ? AND user_id = ?", order.ID, userID).First(&assignment).Error
		if err == nil {
			isAssignment = true // 如果查询到了接单记录，则标记为已接单
		} else if !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, 0, err // 如果发生其他错误，则直接返回
		}

		// 转换订单数据并设置收藏状态、接单状态和用户信息
		orderResponse := convertCusOrderToResponse(order)
		orderResponse.IsFavorite = &isFavorited
		orderResponse.UserAvatar = user.Avatar     // 设置用户头像
		orderResponse.UserAddress = user.Address   // 设置用户地址
		orderResponse.IsAssignment = &isAssignment // 设置接单状态
		orderResponse.UserNickName = user.Nickname
		orderResponses = append(orderResponses, orderResponse)
	}

	return orderResponses, total, nil
}

func (cusOrderService *CusOrderService) SearchOrders(userID int, queryStr string) (list []customerRes.CusOrderListResponse, total int64, err error) {
	db := global.GVA_DB.Debug().Model(&customer.CusOrder{})
	// 处理紧急程度筛选
	if queryStr != "" {
		db = db.Where("id LIKE ? OR an_require LIKE ? OR item_type LIKE ? OR buss_type LIKE ? OR title LIKE ?",
			"%"+queryStr+"%", "%"+queryStr+"%", "%"+queryStr+"%", "%"+queryStr+"%", "%"+queryStr+"%")
	}

	// 获取记录总数
	err = db.Count(&total).Debug().Error
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	var orders []customer.CusOrder
	// 查询订单数据
	err = db.Find(&orders).Debug().Error
	if err != nil {
		return nil, 0, err
	}

	var orderResponses []customerRes.CusOrderListResponse

	// 遍历订单，检查收藏状态、接单状态，并转换为响应结构
	for _, order := range orders {
		var isFavorited bool
		var isAssignment bool

		// 查询收藏记录
		var favorite customer.CusOrderFavorite
		err := global.GVA_DB.Where("user_id = ? AND order_id = ?", userID, order.ID).First(&favorite).Error
		if err == nil {
			isFavorited = true // 如果查询到了收藏记录，则标记为已收藏
		} else if !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, 0, err // 如果发生其他错误，则直接返回
		}

		// 查询用户信息
		var user customer.CusUser
		err = global.GVA_DB.Where("id = ?", order.OrderUserId).First(&user).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, 0, err // 如果发生其他错误，则返回错误
		}

		// 查询接单状态
		var assignment customer.CusOrderAssignments
		err = global.GVA_DB.Where("order_id = ? AND user_id = ?", order.ID, userID).First(&assignment).Error
		if err == nil {
			isAssignment = true // 如果查询到了接单记录，则标记为已接单
		} else if !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, 0, err // 如果发生其他错误，则直接返回
		}

		// 转换订单数据并设置收藏状态、接单状态和用户信息
		orderResponse := convertCusOrderToResponse(order)
		orderResponse.IsFavorite = &isFavorited
		orderResponse.UserAvatar = user.Avatar     // 设置用户头像
		orderResponse.UserAddress = user.Address   // 设置用户地址
		orderResponse.IsAssignment = &isAssignment // 设置接单状态
		orderResponse.UserNickName = user.Nickname
		orderResponses = append(orderResponses, orderResponse)
	}

	return orderResponses, total, nil
}

func (cusOrderService *CusOrderService) GetOptimalCusOrders() ([]customerRes.CusOrderListResponse, error) {
	var orders []customer.CusOrder

	// 获取 status = 3 的订单，并按照 max_price 降序排序，限制结果为前 5 个
	err := global.GVA_DB.Where("status = 3").Debug().
		Order("budget_max desc").
		Limit(5).
		Find(&orders).Error
	if err != nil {
		return nil, err
	}

	var orderResponses []customerRes.CusOrderListResponse
	for _, order := range orders {
		// 查询每个订单的接单人数
		var assignmentCount int64
		err := global.GVA_DB.Model(&customer.CusOrderAssignments{}).
			Where("order_id = ?", order.ID).
			Count(&assignmentCount).Error
		if err != nil {
			return nil, err
		}

		// 构造单独返回结构体
		//orderResponse := customerRes.CusOrderWithAssignmentCountResponse{
		//	Order: convertCusOrderToResponse(order),
		//	//AssignmentCount: assignmentCount, // 单独返回接单人数
		//}

		orderResponses = append(orderResponses, convertCusOrderToResponse(order))
	}

	return orderResponses, nil
}

func (cusOrderService *CusOrderService) UpdateOrderEvaluation(orderID int, orderEva string) error {
	// 更新数据库中的订单评价
	err := global.GVA_DB.Model(&customer.CusOrder{}).
		Where("id = ?", orderID).
		Update("order_eva", orderEva).Error

	return err
}

func (cusOrderService *CusOrderService) GetCusOrdersByStatusAndIsPaid(userid, status int, isPaid *bool, sortBy string, queryStr string) ([]customerRes.CusOrderListResponse, error) {
	var orders []customer.CusOrder
	db := global.GVA_DB.Model(&customer.CusOrder{}).Where("order_user_id = ? AND status = ?", userid, status)

	// 根据 status 为 4 时再增加 IsPaid 的过滤条件
	if status == 4 && isPaid != nil {
		db = db.Where("is_paid = ?", *isPaid)
	}

	// 模糊查询条件
	if queryStr != "" {
		db = db.Where("id LIKE ? OR an_require LIKE ? OR item_type LIKE ? OR buss_type LIKE ?",
			"%"+queryStr+"%", "%"+queryStr+"%", "%"+queryStr+"%", "%"+queryStr+"%")
	}

	// 根据 SortBy 参数进行排序
	switch sortBy {
	case "时间由近及远":
		db = db.Order("created_at DESC")
	case "时间由远及近":
		db = db.Order("created_at ASC")
	case "价格由低到高":
		db = db.Order("budget_max ASC")
	case "价格由高到低":
		db = db.Order("budget_max DESC")
	}

	err := db.Find(&orders).Error
	if err != nil {
		return nil, err
	}

	// 查询每个订单的接单人数，并格式化返回值
	var orderResponses []customerRes.CusOrderListResponse
	for _, order := range orders {
		// 查询 customer.CusOrderAssignments 中该订单的接单人数
		var assignmentCount int64
		err := global.GVA_DB.Model(&customer.CusOrderAssignments{}).
			Where("order_id = ?", order.ID).
			Count(&assignmentCount).Error
		if err != nil {
			return nil, err
		}

		// 使用 convertCusOrderToResponse 并添加接单人数
		orderResponse := convertCusOrderToResponse(order)
		orderResponse.AssignmentCount = assignmentCount
		orderResponses = append(orderResponses, orderResponse)
	}
	return orderResponses, nil
}

func (cusOrderService *CusOrderService) SearchCusOrdersByAnRequire(queryStr string) ([]customerRes.CusOrderListResponse, error) {
	var orders []customer.CusOrder

	// 使用 LIKE 进行模糊查询
	err := global.GVA_DB.Model(&customer.CusOrder{}).
		Where("an_require LIKE ?", "%"+queryStr+"%").
		Find(&orders).Error

	if err != nil {
		return nil, err
	}

	// 使用 convertCusOrderToResponse 格式化返回值
	var orderResponses []customerRes.CusOrderListResponse
	for _, order := range orders {
		orderResponses = append(orderResponses, convertCusOrderToResponse(order))
	}
	return orderResponses, nil
}

func (cusOrderService *CusOrderService) GetEvaluatedOrders() ([]customerRes.CusOrderListResponse, error) {
	var orders []customer.CusOrder
	err := global.GVA_DB.Model(&customer.CusOrder{}).
		Where("order_eva IS NOT NULL AND order_eva != ''").
		Limit(10).
		Find(&orders).Error

	if err != nil {
		return nil, err
	}

	// 使用 convertCusOrderToResponse 格式化返回值
	var orderResponses []customerRes.CusOrderListResponse
	for _, order := range orders {
		orderResponses = append(orderResponses, convertCusOrderToResponse(order))
	}
	return orderResponses, nil
}
func convertCusOrderToSimpleResponse(order customer.CusOrder) customerRes.CusOrderSimpleResponse {
	return customerRes.CusOrderSimpleResponse{
		ID:            order.ID,
		Title:         order.Title,
		Status:        order.Status,
		BudgetMin:     order.BudgetMin,
		BudgetMax:     order.BudgetMax,
		Background:    order.Background,
		ExPrice:       order.ExPrice,
		UrgencyDegree: order.UrgencyDegree,
		Attach:        order.Attach,
		BussType:      order.BussType,
		ItemType:      order.ItemType,
		CreatedAt:     order.CreatedAt.Unix(),
		UpdatedAt:     order.UpdatedAt.Unix(),
		BackContent:   order.BackContent,
	}
}

// convertCusOrderToResponse 将 CusOrder 转换为 CusOrderListResponse
func convertCusOrderToResponse(order customer.CusOrder) customerRes.CusOrderListResponse {
	return customerRes.CusOrderListResponse{
		ID:              order.ID,
		Title:           order.Title,
		Status:          order.Status,
		IsFirst:         order.IsFirst,
		BudgetMin:       order.BudgetMin,
		BudgetMax:       order.BudgetMax,
		ExPrice:         order.ExPrice,
		AddPrice:        order.AddPrice,
		RefundPrice:     order.RefundPrice,
		UrgencyDegree:   order.UrgencyDegree,
		Background:      order.Background,
		AnRequire:       order.AnRequire,
		Other:           order.Other,
		Attach:          order.Attach,
		BussSubType:     order.BussSubType,
		BussType:        order.BussType,
		ItemType:        order.ItemType,
		InvolvedField:   order.InvolvedField,
		ResearchPurpose: order.ResearchPurpose,
		ResearchDesign:  order.ResearchDesign,
		DataIsFinish:    order.DataIsFinish,
		DataType:        order.DataType,
		OrderEva:        order.OrderEva,
		OrderUserId:     order.OrderUserId,
		CreatedAt:       order.CreatedAt.Unix(),
		UpdatedAt:       order.UpdatedAt.Unix(),
		BackContent:     order.BackContent,
		Specialty:       order.Specialty,
		Deadline:        order.Deadline,
		IsPaid:          &order.IsPaid,
	}
}
